package com.blacktry.service.impl;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blacktry.entity.easypoidata.TableRenderPolicy;
import com.blacktry.entity.model.Calendar;
import com.blacktry.entity.model.Timetable;
import com.blacktry.entity.model.request.CalendarRequest;
import com.blacktry.mapper.CalendarMapper;

import com.blacktry.service.CalendarService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.RowRenderData;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CalendarServiceImpl extends ServiceImpl<CalendarMapper, Calendar> implements CalendarService {

    @Override
    public Page<Calendar> selectCalendar(CalendarRequest calendarRequest, Page<Calendar> page) {
        return this.baseMapper.selectCalendar(calendarRequest,page);
    }

    @Override
    public void exportCalendar(HttpServletResponse response, CalendarRequest calendarRequest) throws IOException {

        String TimeNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(java.util.Calendar.getInstance().getTime());
        String year = new SimpleDateFormat("yyyy").format(java.util.Calendar.getInstance().getTime());
        String month = new SimpleDateFormat("MM").format(java.util.Calendar.getInstance().getTime());
        String day = new SimpleDateFormat("dd").format(java.util.Calendar.getInstance().getTime());

        Page<Calendar> calendarPage = selectCalendar(calendarRequest, new Page<>(1, 999));
        Calendar calendar = calendarPage.getRecords().get(0);
        // 将 实体类 转换为 Map
        Map<String, Object> data = JSON.parseObject(JSON.toJSONString(calendar), Map.class);
//        System.out.println(map);
//
//        data.put("title", "success");
//        data.put("tableData", "first");
        data.remove("assessmentWay");
        if("闭卷笔试".equals(calendar.getAssessmentWay())){
            data.put("w1","√");
        }else if("口试".equals(calendar.getAssessmentWay())){
            data.put("w2","√");
        }else if("综合实验".equals(calendar.getAssessmentWay())){
            data.put("w3","√");
        }else if("开卷笔试".equals(calendar.getAssessmentWay())){
            data.put("w4","√");
        }else if("论文".equals(calendar.getAssessmentWay())){
            data.put("w5","√");
        }else{
            data.put("w6","√");
        }
        int totalProportion = 0;
        if(data.get("homeworkProportion")!=null){
            totalProportion+=(int)data.get("homeworkProportion");
        }
        if(data.get("testProportion")!=null){
            totalProportion+=(int)data.get("testProportion");
        }
        if(data.get("labProportion")!=null){
            totalProportion+=(int)data.get("labProportion");
        }
        if(data.get("paperProportion")!=null){
            totalProportion+=(int)data.get("paperProportion");
        }
        if(data.get("attendanceProportion")!=null){
            totalProportion+=(int)data.get("attendanceProportion");
        }
        if(data.get("performanceProportion")!=null){
            totalProportion+=(int)data.get("performanceProportion");
        }
        if(data.get("otherProportion")!=null){
            totalProportion+=(int)data.get("otherProportion");
        }
        data.put("totalProportion",totalProportion);

        data.remove("textBook");
        data.remove("referenceBook");

        if(calendar.getTextBook()!=null){
            String[] textBooks = calendar.getTextBook().split("-");
            data.put("textBookName",textBooks[0]);
            data.put("textBookAuthor",textBooks[1]);
            data.put("textBookPublish",textBooks[2]);
        }
        if(calendar.getReferenceBook()!=null){
            String[] referenceBooks = calendar.getReferenceBook().split("-");
            data.put("referenceBookName",referenceBooks[0]);
            data.put("referenceBookAuthor",referenceBooks[1]);
            data.put("referenceBookPublish",referenceBooks[2]);
        }

        List<RowRenderData> list = new ArrayList<>();
        for (int i = 0; i < calendar.getTimetableList().size(); i++) {
            Timetable timetable = calendar.getTimetableList().get(i);
            RowRenderData rowdata = RowRenderData.build(timetable.getRealTime(),timetable.getWeekNum().toString(),timetable.getTeachOrder().toString(),timetable.getContent(),timetable.getPeriod().toString(),timetable.getSchedule());
            list.add(rowdata);
        }
        data.put("year",year);
        data.put("month",month);
        data.put("day",day);
        data.put("timetableList", list);

        Configure config = Configure.newBuilder().customPolicy("timetableList", new TableRenderPolicy()).build();
        ClassPathResource resource = new ClassPathResource("templates/calendar.docx");
        XWPFTemplate template = XWPFTemplate.compile(resource.getStream(), config).render(data);
        String fileName = calendar.getCourseName() + "教学日历-" + calendar.getTeaName() + "-" + year + ".docx";

//        fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
        fileName = URLEncoder.encode(fileName, "utf-8");

        response.setContentType("application/msword;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Param", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        OutputStream out = response.getOutputStream();
        template.write(out);
        out.flush();
        out.close();
        template.close();
    }
}
